from openpyxl import load_workbook
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os

def excel_to_word(excel_path, word_path=None,table_style="Table Grid"):
    """
        将Excel表格转换为Word文档
        参数:
            excel_path (str): Excel文件路径
            word_path (str): 输出的Word文件路径(可选)
            table_style (str): Word表格样式(默认为'Table Grid')
        """
    #加载Excel文件
    wb=load_workbook(excel_path)
    ws=wb.active#获取当前工作表
    #若没有指定word路径，则使用Excel形同路径和名称
    if word_path is None:
        word_path=os.path.splitext(excel_path)[0]+'.docx'
    #创建Word文档
    doc=Document()

    #添加标题（使用Excel文件名）
    title=os.path.splitext(os.path.basename(excel_path))[0]
    heading=doc.add_heading(title,1)
    heading.alignment=WD_ALIGN_PARAGRAPH.CENTER

    #添加表格
    table=doc.add_table(rows=ws.max_row,cols=ws.max_column)
    table.style=table_style

    #填充表格内容
    for row_idx,row in enumerate(ws.iter_rows(values_only=True),start=0):
        for col_idx,value in enumerate(row,start=0):
            cell=table.cell(row_idx,col_idx)
            cell.text=str(value) if value is not None else ''

            #设置单元格字体大小
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.size=Pt(10)

    #保存Word文档
    doc.save(word_path)
    print(f"Word文档已保存至{word_path}")

    if __name__ == '__main__':
        #示例用法
        excel_file=input("请输入Excel文件路径：").strip('"')
        if os.path.exists(excel_file):
            excel_to_word(excel_file)
        else:
            print("文件不存在,请检查路径！")